package com.jianggujin.modulelink.test;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class MimeTypeXMLParser {
    @Test
    public void parse() throws Exception {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        DefaultHandler handler = new DefaultHandler() {
            int flag = 0;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                if ("extension".equals(localName)) {
                    flag = 1;
                } else if ("mime-type".equals(localName)) {
                    flag = 2;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (flag == 1) {
                    System.out.print(new String(ch, start, length));
                    System.out.print("=");
                } else if (flag == 2) {
                    System.out.println(new String(ch, start, length));
                }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                flag = 0;
            }
        };
        xmlReader.setContentHandler(handler);
        xmlReader.setEntityResolver(handler);
        xmlReader.setErrorHandler(handler);
        xmlReader.setDTDHandler(handler);
        xmlReader.parse(new InputSource(getClass().getResourceAsStream("mime-type.xml")));
    }
}
